package study.zhangbo.lock.web;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import study.zhangbo.lock.distributed.redis.RedisLockService;
import study.zhangbo.lock.distributed.redis.RedisLockUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhangbo on 2020/10/29.
 */
@Slf4j
@RestController
public class RedisLockTestController {


    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private RedisLockUtils redisLockUtils;


    private static final ConcurrentMap<String, AtomicInteger> CONCURRENT_MAP = new ConcurrentHashMap<>();

    private static AtomicInteger atomicInteger = new AtomicInteger(1);

    @GetMapping("/redis/test")
    public Object getRedis() {
        boolean nx = redisLockUtils.setNx("test", "test");
        System.out.println("nx:" + nx);
        String value = redisLockUtils.getValue("test");
        System.out.println(value);
        return value;
    }

    @GetMapping("/redis/listener/{key}")
    public Object listener(@PathVariable(value = "key") String key) {
        String value = null;
        while (true) {
            String newVlue = redisLockUtils.getValue(key);
            if(null != newVlue && !newVlue.equals(value)) {
                value = newVlue;
                System.out.println("value:" + value);
            }
        }
    }


    @GetMapping("/redis/lock/{key}")
    public Object testLock(@PathVariable(value = "key") String key) {
        try {
            redisLockService.lock(key);
            //发送请求调用逻辑
            System.out.println("开始执行方法：" + atomicInteger.getAndIncrement());
            HttpResponse send = HttpRequest.get("http://localhost:8080/redis/print/" + key).send();
            if (send.statusCode() != 200) {
                System.out.println("返回请求异常,code:" + send.statusCode());
            }
        } finally {
            redisLockService.unlock();
        }
        return "success";
    }


    @GetMapping("/redis/print/{key}")
    public Object print(@PathVariable(value = "key") String key) {
        if (!CONCURRENT_MAP.containsKey(key)) {
            CONCURRENT_MAP.put(key, new AtomicInteger(1));
        }
        System.out.println("接收到请求：" + key + ",序号：" + CONCURRENT_MAP.get(key).getAndIncrement());
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            log.error("休眠异常：{}", e);
        }
        return "success";
    }


}
